﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using NHibernate;
using ShopSpace.Infrastructure.Data;

namespace ShopSpace.Infrastructure.UI.Web
{
	/// <summary>
	/// Manages the creation and disposal
	/// of a UnitOfWork in a web app
	/// </summary>
	public class UnitOfWorkModule : IHttpModule
	{
		#region IHttpModule Members

		private UnitOfWork unitOfWork;

		public ISessionFactory SessionFactory
		{
			get;
			set;
		}

		public void Dispose()
		{
			this.unitOfWork.Dispose();
		}

		public void Init(HttpApplication context)
		{
			this.SessionFactory = ServiceLocator.Get<ISessionFactory>();
			context.BeginRequest += new EventHandler(context_BeginRequest);
			context.EndRequest += new EventHandler(context_EndRequest);
			context.Error += new EventHandler(context_Error);
		}

		void context_Error(object sender, EventArgs e)
		{
			this.unitOfWork.Dispose();
		}

		void context_EndRequest(object sender, EventArgs e)
		{
			this.unitOfWork.Dispose();
		}

		void context_BeginRequest(object sender, EventArgs e)
		{
			this.unitOfWork = new UnitOfWork(this.SessionFactory);
		}

		#endregion
	}
}
